var fs = require('fs');

let GlobalOrders = []; // 保存从文件中读出的数据

// 从Json文件中读数据
function readOrder(orders){
    fs.readFile('./order.json', 'utf-8', (err, data)=>{
        if(err) throw err;
        orders = JSON.parse(data);
        console.log(orders);
    });
}

// readOrder(GlobalOrders);

let goods = [
    {
        gId:'003',
        goodName:'大疆无人机',
        gPrice: 5888
    },
    {
        gId:'004',
        goodName:'比亚迪海豹',
        gPrice: 229999
    }
];

// 添加数据到文件中
function addOrder(goods){
    fs.readFile('./order.json', 'utf-8', (err, data)=>{
        if(err) throw err;
        GlobalOrders = JSON.parse(data);
        console.log('添加写入前：');
        console.log(GlobalOrders);
        for(var g of goods){
            GlobalOrders.push(g);
        }
        console.log('添加写入后：');
        console.log(GlobalOrders);
        fs.writeFile('./order.json', JSON.stringify(GlobalOrders) , (err)=>{
            if(err) throw err;
        });
    });
}

// 修改文件中指定的数据
function modifyOrder(key, goods){
    fs.readFile('./order.json', 'utf-8', (err, data)=>{
        if(err) throw err;
        GlobalOrders = JSON.parse(data);
        console.log('修改前：');
        console.log(GlobalOrders);
        for(var g of GlobalOrders){
            if(g.gId == key){
                g.goodName = goods.goodName;
                g.gPrice = goods.gPrice;
            }
        }
        console.log('修改后：');
        console.log(GlobalOrders);
        fs.writeFile('./order.json', JSON.stringify(GlobalOrders) , (err)=>{
            if(err) throw err;
        });
    });
}

// 删除文件中指定的数据
function delOrder(key){
    fs.readFile('./order.json', 'utf-8', (err, data)=>{
        if(err) throw err;
        GlobalOrders = JSON.parse(data);
        console.log('删除前：');
        console.log(GlobalOrders);
        var pos = -1;
        for(var i = 0; i<GlobalOrders.length; i++){
            if(GlobalOrders[i].gId == key){
                pos = i;
            }
        }
        if(pos >=0 ) GlobalOrders.splice(pos,1);

        console.log('删除后：');
        console.log(GlobalOrders);
        fs.writeFile('./order.json', JSON.stringify(GlobalOrders) , (err)=>{
            if(err) throw err;
        });
    });
}

// addOrder(goods);

// modifyOrder('001', {
//     goodName: '华为手机P60',
//     gPrice: 12666
// });

delOrder('002');
